package jmine.tec.utils.spring;

import java.io.IOException;

import java.net.URI;
import java.util.HashSet;

import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.core.io.Resource;
import org.xml.sax.InputSource;

/**
 * BeanDefinitionReader que utiliza cache.
 * @author cesar
 */
public class CachingXmlBeanDefinitionReader extends XmlBeanDefinitionReader {
	
	private final HashSet<URI> alreadyLoaded = new HashSet<URI>();

	/**
	 * Create new XmlBeanDefinitionReader for the given bean factory.
	 * 
	 * @param registry
	 *            the BeanFactory to load bean definitions into, in the form of
	 *            a BeanDefinitionRegistry
	 */
	public CachingXmlBeanDefinitionReader(BeanDefinitionRegistry registry) {
		super(registry);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource) {
        try {
            if (alreadyLoaded.contains(resource.getURI())) {
                return 0;
            }
            
            int loadedBeans = super.doLoadBeanDefinitions(inputSource, resource);
            alreadyLoaded.add(resource.getURI());
            return loadedBeans;
        } catch (IOException e) {
            return super.doLoadBeanDefinitions(inputSource, resource);
        }
	}
}
